/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UdpClient.java
 *
 * Created on Oct 7, 2010, 7:24:37 AM
 */
package dnstry;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.*;
import java.net.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author student
 */
public class UdpClient extends javax.swing.JFrame {

    /** Creates new form UdpClient */
    public DatagramPacket packet;
    public DatagramPacket packet2;
    public DatagramSocket socket;
    public DatagramSocket socket2;
    public DnsQuery query;

    public UdpClient() {
        initComponents();
        try {
            //socket = new DatagramSocket(1500, InetAddress.getByName("127.0.0.1"));
          //  socket = new DatagramSocket(1500);
         //   socket.setSoTimeout(3000);
        //    System.out.println("online");
        query = new DnsQuery();
        } catch (Exception ex) {
            Logger.getLogger(UdpClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        ShowText = new javax.swing.JTextArea();
        Message_field = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        address_bar = new javax.swing.JTextField();
        jInverseLookupBox = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        ShowText.setColumns(20);
        ShowText.setRows(5);
        jScrollPane1.setViewportView(ShowText);

        Message_field.setText("www.yahoo.com");
        Message_field.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Message_fieldActionPerformed(evt);
            }
        });

        jButton1.setText("Send");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        address_bar.setText("4.2.2.2");

        jInverseLookupBox.setText("Inverse Lookup(not functional)");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Message_field, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jInverseLookupBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addComponent(address_bar, javax.swing.GroupLayout.DEFAULT_SIZE, 455, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 455, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(address_bar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Message_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jInverseLookupBox))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
//            // TODO add your handling code here:
//            //socket.connect(InetAddress.getLocalHost(),8888);
            //           String text = Message_field.getText();
           String[] ipList = query. getIp(Message_field.getText(),address_bar.getText());
            for ( int i = 0 ; i < ipList.length; i ++)
            {
                if( ipList[i] != null)
                ShowText.append("\n------>"+ipList[i] );
            }
           ShowText.append("\n ===> inedAddress" + query.getIneAddress(Message_field.getText(),address_bar.getText()).toString());

//            byte[] bytes = formDNSReq(Message_field.getText());
//            packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(address_bar.getText()/*"81.180.223.1""4.2.2.2"*/), 53);
//            int len = bytes.length;
//
//            socket.send(packet);
////            System.out.println("objSet");
//            packet2 = new DatagramPacket(new byte[512], 512);
//            socket.receive(packet2);
//
//            bytes = packet2.getData();
//
//            System.out.println();
//            ShowText.append("recieved ");
//            ShowText.append("\n");
//            for (int i = 0; i < packet2.getLength(); i++) {
//                int aux = bytes[i];
//                //       Byte au_ = new Byte(aux);
//
//
//                int val = bytes[i] & 0x80;
//
//                val += bytes[i] & 0x7F;
//
//                System.out.print(" " + bytes[i] + " ");
//                if (aux > 'A' - 1) {
//                    ShowText.append(" " +/*bytes[i]*/ (char) (val)/*+":"+aux*/ + " ");
//                } else {
//                    ShowText.append(" " +/*bytes[i]*/ val/*+":"+aux*/ + " ");
//                }
//                if ((i % 8 == 0) && (i != 0)) {
//                    ShowText.append("\n");
//                }
//            }
//            System.out.println("len:" + len);
//            DnsAnswer answer = new DnsAnswer(bytes, len);
//            ShowText.append(" \n arCount:" + answer.getAnswerRecordCount());
//            ShowText.append(" \n nsCount:" + answer.getNameServerCount());
//            ShowText.append(" \n addCount:" + answer.getAdditionRecordsCount());
//            answer.parse();
//            for (int i = 0; i < answer.entryList.size(); i++) {
//                ShowText.append("\n parsed response : " + answer.entryList.get(i).toString());
//            }
//            FileWriter fstream = new FileWriter("myFile.txt", true);
//            BufferedWriter out = new BufferedWriter(fstream);
//
//            //Close the output stream
//
//            for (int i = 0; i < answer.entryList.size(); i++) {
//
//                out.write("address : " + Message_field.getText() + " from : " + address_bar.getText() + " : " + answer.entryList.get(i).toString() + "\n");
//                ShowText.append("\n --->" + answer.entryList.get(i).getIP());
//                if (answer.entryList.get(i).getType() == 1) {
//                    out.write("ip: " + answer.entryList.get(i).getIP() + "\n");
//                }
//            }
//            out.close();
        } catch (Exception ex) {
            Logger.getLogger(UdpClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void Message_fieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Message_fieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_Message_fieldActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new UdpClient().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField Message_field;
    private javax.swing.JTextArea ShowText;
    private javax.swing.JTextField address_bar;
    private javax.swing.JButton jButton1;
    private javax.swing.JCheckBox jInverseLookupBox;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

}
